package com.xzx.shop_front_api.controller;

import com.xzx.shop_front_api.entity.Cart;
import com.xzx.shop_front_api.entity.Goods;
import com.xzx.shop_front_api.entity.Order;
import com.xzx.shop_front_api.entity.OrderItem;
import com.xzx.shop_front_api.service.*;
import com.xzx.shop_front_api.utils.JsonResult;
import com.xzx.shop_front_api.utils.Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 订单控制器类
 */
@RestController
@RequestMapping("api/order")
public class OrderController {
    @Autowired
    private CartService cartService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private Order order;
    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private OrderItem orderItem;
    @Autowired
    private CouponService couponService;

    /**
     *
     * @param memberId
     * @param amount
     * @param discountAmount
     * @param couponId 对应 shop_members_coupons.id
     * @param addressId 对应的shop_addresses.id
     * @return
     */
    @PostMapping("create")
    public JsonResult create(@RequestParam("member_id") int memberId,
                             @RequestParam("amount") Double amount,
                             @RequestParam("discount_amount") Double discountAmount,
                             @RequestParam(value = "coupon_id",defaultValue = "0") int couponId,
                             @RequestParam("address_id") int addressId,
                             @RequestParam("address") String address,
                             @RequestParam("mark") String mark,
                             @RequestParam("ship_fee") Double shipFee,
                             @RequestParam("receiver_name") String receiverName,
                             @RequestParam("receiver_phone") String receiverPhone

                             ) {

        List<OrderItem> orderItemsLists = new ArrayList<>();
        //查购物车
        List<Cart> cartLists = cartService.getCartListByMemberIdSelected(memberId);
        for (Cart cart : cartLists) {
            int goodsId = cart.getGoodsId();
            //判断商品是否有效
            Goods goodsInfo = goodsService.getGoodsById(goodsId);
            if (goodsInfo == null ) {
                return JsonResult.failed("该商品不存在");
            }

            if (goodsInfo.getStatus() !=1) {
                return JsonResult.failed("该商品已经下架");
            }
            //判断价格是否正确
            if (goodsInfo.getSalePrice() != cart.getPayPrice()) {
                return JsonResult.failed("该商品价格不正确");

            }
            //判断库存
            int stock = goodsInfo.getStock();//实际库存
            int lockStock = goodsInfo.getLockStock();//锁定库存
            int sellStock = stock - lockStock;
            if (sellStock < cart.getQuantity()) {
                return JsonResult.failed("该商品已售完。");
            }
            OrderItem orderItem = new OrderItem();//初始化对象
            System.out.println("商品名:"+goodsInfo.getGoodsName());
            orderItem.setGoodsName(goodsInfo.getGoodsName());
            orderItem.setGoodsId(goodsId);
            orderItem.setGoodsImage(goodsInfo.getMainImage());
            orderItem.setBuyQuantity(cart.getQuantity());
            orderItem.setGoodsPrice(cart.getPayPrice());
            orderItem.setSubTotal(cart.getPayPrice()*cart.getQuantity());
            orderItemsLists.add(orderItem);

        }

        //订单编号T20251120150234+3222
        String orderSn = "T" + Tool.getCurrentDate("yyyyMMddHHmmss");
        order.setOrderSn(orderSn);
        order.setMemberId(memberId);
        order.setAmount(amount);
        order.setDiscountAmount(discountAmount);
        //实际支付金额计算 总金额-优惠金额+运费
        double payAmount = amount - discountAmount + shipFee;
        order.setPayAmount(payAmount);
        order.setShipFee(shipFee);
        order.setReceiverName(receiverName);
        order.setReceiverPhone(receiverPhone);
        order.setReceiverAddr(address);
        order.setMark(mark);
        order.setCreatedTime(Tool.getCurrentTime());
        //创建
        orderService.insertOrder(order);
        //添加订单商品表
        Long orderId = order.getId();
        for (OrderItem orderItem : orderItemsLists) {
            orderItem.setOrderId(orderId);
            orderItem.setCreatedTime(Tool.getCurrentTime());
        }
        orderItemService.insertOrderItem(orderItemsLists);

        //优惠券处理
        if (couponId > 0) {
            couponService.updateCouponInfo(couponId,1,Tool.getCurrentTime(),orderId);
        }
        //锁定库存
        return JsonResult.success("ok",null);

    }
}
